package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.user.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;

// 该任务类用于
// 当用户订单超时未支付后将订单状态修改为已取消
// 每分钟执行一次
// 每晚凌晨1点处理派送中任务，将其修改为已完成
@Component
@Slf4j
public class OrderStatusDealWithTask {
    @Autowired
    private OrderMapper orderMapper;

    @Scheduled(cron = "0 0/1 * * * ?")
    public void cancelOrderOfUnPay() {
        log.info("取消未支付订单任务启动,每分钟执行一次");
        // 获取超时订单
        List<Orders> ordersList = orderMapper.getAllByStatusAndTime(Long.valueOf(Orders.PENDING_PAYMENT), LocalDateTime.now().minusMinutes(15));

        // 将超时的订单的订单状态改为取消
        // 并设置对应取消信息
        if (ordersList != null && !ordersList.isEmpty()) {
            log.info("当前支付超时订单信息为：{}", ordersList);
            ordersList.forEach(e -> {
                e.setStatus(Orders.CANCELLED);
                e.setCancelTime(LocalDateTime.now());
                e.setCancelReason("支付超时，自动取消");
                orderMapper.update(e);
            });
            return;
        }
        log.info("当前无订单支付超时");

    }

    @Scheduled(cron = "0 0 1 * * ? ")
    public void updateOrderStatusToCompleted() {
        // 每天 00:00:00
        LocalDateTime localDateTime = LocalDateTime.now().minusHours(1);
        // 查询每天 晚上十二点前下单 但凌晨一点过后 订单状态仍是派送中的异常订单
        List<Orders> ordersList = orderMapper.getAllByStatusAndTime(Long.valueOf(Orders.DELIVERY_IN_PROGRESS), localDateTime);
        // 修改其订单状态为完成
        if (ordersList != null && !ordersList.isEmpty()) {
            log.info("当前派送超时订单信息为：{}", ordersList);
            ordersList.forEach(e -> {
                e.setStatus(Orders.COMPLETED);
//                e.setDeliveryTime(LocalDateTime.now());
                orderMapper.update(e);
            });
            return;
        }
        log.info("当前无派送超时订单信息");
    }

}
